package edu.sctu.lab04.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author:Mrzhang
 * @Description:
 * @Date:2018.06.18 11:33
 **/
public class PermissionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String servletPath = request.getServletPath();
        HttpSession session = request.getSession();

        String isLogin = (String) session.getAttribute("isLogin");

        if (servletPath != null && (servletPath.equals("/login")) ||
                (servletPath.equals("/register")) ||
                (servletPath.equals("/login.jsp")) ||
                (servletPath.equals("/register.jsp"))) {
            filterChain.doFilter(request,response);
        }else {
            if (isLogin!=null&& isLogin.equals("true")){
                filterChain.doFilter(request,response);

            }else if (isLogin==null){
                request.setAttribute("msg","登录失败请重新登录！！</br>");
                request.setAttribute("return_uri",servletPath);
                RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");
                dispatcher.forward(request,response);
            }else   {
                request.setAttribute("msg","你尚未登录！");
                request.setAttribute("return",servletPath);
                RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");
                dispatcher.forward(request,response);
            }
        }
    }
}
